package com.seres.gate.filter;

import cn.hutool.http.HtmlUtil;
import com.alibaba.fastjson.JSONObject;
import com.seres.enums.ErrorEnum;
import com.seres.response.ApiResponse;
import com.seres.util.StringUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import redis.clients.jedis.params.Params;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Description : xss攻击过滤
 * @ClassName : XssFilter
 * @Author : 程磊
 * @Date: 2020-07-13 13:55
 */
@Component
@Slf4j
public class XssFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取当前请求上下文，在这个上下文基础上可以做很多事情了。具体自己查看API。
        RequestContext context = RequestContext.getCurrentContext();
        //获取原始Htpp请求，有这个对象也可以做很多事情了。
        HttpServletRequest request = context.getRequest();
        String queryString = request.getQueryString();
        if(StringUtils.isNotBlank(queryString)){
            context.addZuulRequestHeader("queryString",queryString);
        }
        if(StringUtils.equals(request.getMethod(), HttpMethod.OPTIONS.name())){
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.NO_CONTENT.value());
            return null;
        }
        Map<String,String[]> parmas = request.getParameterMap();
        for(Map.Entry<String,String[]> entry : parmas.entrySet()){
            for(String param : entry.getValue()){
                if(!StringUtils.equals(param, HtmlUtil.cleanHtmlTag(param))){
                    setUnauthorizedResponse(context,ErrorEnum.ERROR_CHARACTER);
                }
            }
        }
        return null;
    }


    /**
     * 设置 400 无权限状态
     */
    private void setUnauthorizedResponse(RequestContext requestContext, ErrorEnum errorEnum) {
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(HttpStatus.BAD_REQUEST.value());
        requestContext.getResponse().setContentType("application/json;charset=UTF-8");
        requestContext.setResponseBody(JSONObject.toJSONString(ApiResponse.builder().code(errorEnum.getCode()).msg(errorEnum.getMsg()).build()));
    }
}
